import 'package:flutter/material.dart';
import '../models/exchange_card.dart';
import '../models/exchange_request.dart';
import '../service/exchange_service.dart';
import '../widgets/exchange_request_item.dart';
import '../widgets/exchange_success_dialog.dart';

class EcyExchangeRequestsPage extends StatefulWidget {
  // final ExchangeCard card;

  const EcyExchangeRequestsPage({
    Key? key,
    // required this.card,
  }) : super(key: key);

  @override
  _EcyExchangeRequestsPageState createState() => _EcyExchangeRequestsPageState();
}

class _EcyExchangeRequestsPageState extends State<EcyExchangeRequestsPage> {
  final ExchangeService _exchangeService = ExchangeService();
  List<ExchangeRequest> _requests = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    // _loadRequests();
  }

  // Future<void> _loadRequests() async {
  //   setState(() => _isLoading = true);
  //   try {
  //     final requests = await _exchangeService.getCardExchangeRequests(widget.card.id);
  //     setState(() {
  //       _requests = requests;
  //       _isLoading = false;
  //     });
  //   } catch (e) {
  //     setState(() => _isLoading = false);
  //     ScaffoldMessenger.of(context).showSnackBar(
  //       SnackBar(content: Text('加载交换申请失败，请重试')),
  //     );
  //   }
  // }

  Future<void> _handleRequest(ExchangeRequest request, bool accept) async {
    try {
      final success = await _exchangeService.handleExchangeRequest(
        requestId: request.id,
        accept: accept,
      );

      if (success) {
        if (accept) {
          // 显示交换成功弹窗
          await showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) => ExchangeSuccessDialog(
              card: request.offeredCard,
              onConfirm: () => Navigator.of(context).pop(),
            ),
          );
          Navigator.of(context).pop(true); // 返回上一页
        } else {
          // 从列表中移除被拒绝的请求
          setState(() {
            _requests.removeWhere((r) => r.id == request.id);
          });
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('处理交换申请失败，请重试')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('处理交换申请失败，请重试')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          '我的交换申请',
          style: TextStyle(
            color: Colors.black,
            fontSize: 18,
            fontWeight: FontWeight.w500,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              // TODO: 显示规则页面
            },
            child: Text(
              '规则',
              style: TextStyle(
                color: Colors.black54,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : _requests.isEmpty
              ? Center(
                  child: Text(
                    '暂无交换申请',
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 16,
                    ),
                  ),
                )
              : ListView.builder(
                  itemCount: _requests.length,
                  itemBuilder: (context, index) {
                    final request = _requests[index];
                    return ExchangeRequestItem(
                      request: request,
                      onAccept: () => _handleRequest(request, true),
                      onReject: () => _handleRequest(request, false),
                    );
                  },
                ),
    );
  }
} 